package cn.maxwell.controller;

import cn.maxwell.domain.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/loadById/{id}")
    // 标签进行方法单独熔断
    @HystrixCommand(fallbackMethod = "fallbackLodById")
    public User loadById(@PathVariable("id") Long id){
        //发送http请求调用 user的服务，获取user对象 ： RestTemplate
        //目标资源路径：user的ip,user的端口，user的Controller路径
        //String url = "http://localhost:1030/user/loadById/"+id;
        String url = "http://user-server/user/loadById/"+id;

        //发送http请求
        return restTemplate.getForObject(url,User.class);
    }


    /**
     * 兜底方法：当真正的接口坏掉时走这里，给用户返回兜底数据（服务降级）
     * @param id
     * @return
     */
    public User fallbackLodById(@PathVariable("id") Long id){
        User user = new User();
        user.setId(-1L);
        user.setName("服务不可达");
        user.setSex(-1);
        return user;
    }
}
